package library.service;

import library.dao.DaoManager;
import library.dao.DaoManagerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import library.exception.DataException;

public class ServiceInvocationHandlerImpl implements InvocationHandler {

    private Service service;

    public ServiceInvocationHandlerImpl(Service service) {
        this.service = service;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] arguments)
            throws Throwable {
        DaoManager daoManager = null;
        try {
            daoManager = DaoManagerFactory.getInstance();
            service.setManager(daoManager);
            Object result = method.invoke(service, arguments);
            daoManager.transactionCommit();
            return result;
        } catch (DataException e) {
            try {
                daoManager.transactionRollback();
                e.printStackTrace();
            } catch (DataException e1) {
            }
            throw e;
        } finally {
            if (daoManager != null) {
                daoManager.close();
            }
        }
    }
}
